package com.yz.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yz.book.entity.Product;
import com.yz.book.es.ESProductRepository;
import com.yz.book.mapper.ProductMapper;
import com.yz.book.service.ProductService;
import com.yz.book.vo.EsProduct;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ste
 * @since 2023-02-04 03:37:37
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {


    @Autowired
    ProductMapper productMapper;

    @Autowired
    ESProductRepository esProductRepository;

    @Override
    public Page<Product> searchBySQL(Page<Product> page, String keyword) {

        //sql模糊查询
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("product_name",keyword);

        Page<Product> productPage = productMapper.selectPage(page, queryWrapper);


        return productPage;

    }


    @Override
    public Page<EsProduct> searchByES(Integer currentPage, Integer pageSize, String keyword) {
        //es查询

        //构建查询条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();

        //query
        nativeSearchQueryBuilder.withQuery(QueryBuilders.multiMatchQuery(keyword,"productName"));

        //分页条件
        //注意: es中的分页是从第0页开始的
        nativeSearchQueryBuilder.withPageable(PageRequest.of(currentPage-1,pageSize));

        //排序
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("buyCount").order(SortOrder.DESC));

        org.springframework.data.domain.Page<EsProduct> esBookPage = esProductRepository.search(nativeSearchQueryBuilder.build());

        //将 Es的page 转换 mybatisPlus的 page
        Page<EsProduct> productPage = new Page<>(currentPage,pageSize);
        productPage.setPages(esBookPage.getTotalPages());
        productPage.setTotal(esBookPage.getTotalElements());
        productPage.setRecords(esBookPage.getContent());

        return productPage;
    }

}
